package com.me.myapplication;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class MainActivity extends AppCompatActivity implements PoiSearch.OnPoiSearchListener{

    MapView mMapView;
    PoiSearch poiSearch;
    EditText input;
    Polygon polygon;
    Polyline polyline;
    AMap aMap;

    Button ifStartDraw;
    Button searchPOI;
    Button searchPlace;
    Button returnPre;
    Button reDraw;
    ImageButton tips;

    Toolbar toolbar;

    Stack<Marker> markers;

    private List<LatLng> points;
    private StringBuilder results = new StringBuilder();
    private final static int PAGE_NUMS = 40;
    private static boolean hasStarted = false;
    private static int currentPage = 0;

    HashMap<String, Integer> typeCounts;

    class BtnState{
        final static int ON_DRAW = 0;
        final static int ON_CLOSE = 1;
    }

    private static int drawState = BtnState.ON_CLOSE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        setAction();
        setToolbar();
        mMapView.onCreate(savedInstanceState);
    }

    private void initData(){
        aMap = mMapView.getMap();
        aMap.setMaxZoomLevel(18);
        aMap.setMinZoomLevel(6);
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(28.19833979303484, 112.95797855135542)));

        points = new ArrayList<>();
        markers = new Stack<>();
        typeCounts = new HashMap<>();

        for(String type: SearchUtil.type){
            typeCounts.put(type, 0);
        }
    }

    private void initView(){
        mMapView = findViewById(R.id.map);
        ifStartDraw = findViewById(R.id.btn_start_drawer);
        input = findViewById(R.id.input);
        searchPOI = findViewById(R.id.btn_get_data);
        searchPlace = findViewById(R.id.btn_search_place);
        returnPre = findViewById(R.id.btn_cancel);
        reDraw = findViewById(R.id.btn_re_draw);
        toolbar = findViewById(R.id.toolbar);
        tips = findViewById(R.id.i_btn_tips);
    }

    private void setToolbar(){
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if(null != actionBar){
            actionBar.setTitle("高德POI获取器");
        }
    }

    private void setAction(){

        tips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, TipsActivity.class);
                startActivity(intent);
            }
        });

        reDraw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                points.clear();
                while (!markers.empty()){
                    markers.pop();
                }
                if(polygon != null){
                    polygon.remove();
                }
                if(polyline != null){
                    polyline.remove();
                }
                aMap.clear();
                drawState = BtnState.ON_DRAW;
            }
        });

        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if(BtnState.ON_DRAW == drawState){
                    points.add(latLng);
                    draw(points);
                }
            }
        });

        returnPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(BtnState.ON_DRAW == drawState){
                    int size = points.size();
                    if(size > 0){
                        points.remove(points.size() - 1);
                        markers.pop().remove();
                        size--;
                    }else{
                        return;
                    }

                    if(size >= 3){
                        drawPolygon(points);
                        drawLine(points);
                    }else if(size > 1){
                        if(null != polygon){
                            polygon.remove();
                        }
                        drawLine(points);
                    }else if(size == 1){
                        if(null != polyline){
                            polyline.remove();
                        }
                    }
                }
            }
        });

        searchPlace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "功能暂未完成哦", Toast.LENGTH_LONG).show();
            }
        });

        searchPOI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchPOI();
            }
        });

        ifStartDraw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(BtnState.ON_DRAW == drawState){
                    drawState = BtnState.ON_CLOSE;
                    ifStartDraw.setText("开始选区");
                }else if(BtnState.ON_CLOSE == drawState){
                    drawState = BtnState.ON_DRAW;
                    ifStartDraw.setText("暂停选区");
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    private void searchPOI(){
        results = new StringBuilder(); //清空上次的结果
        currentPage = 0;
        hasStarted = false;

        if(points.size() < 3){
            Toast.makeText(this, "不是多边形", Toast.LENGTH_LONG).show();
            return;
        }

        List<LatLonPoint> latLonPoints = new ArrayList<>();
        for(LatLng point: points){
            latLonPoints.add(new LatLonPoint(point.latitude, point.longitude));
        }

        PoiSearch.Query query = new PoiSearch.Query("", SearchUtil.allTypes, "");
        query.setCityLimit(true);
        query.setPageSize(30);
        for(int i=0; i<= PAGE_NUMS; i++){
            query.setPageNum(i);
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.setBound(new PoiSearch.SearchBound(latLonPoints));
            poiSearch.searchPOIAsyn();
        }
    }


    @Override
    public void onPoiSearched(PoiResult poiResult, int rCode) {
        if (rCode== AMapException.CODE_AMAP_SUCCESS){
            if(0 == poiResult.getPois().size() && hasStarted){
                return;
            }
            if(0 == poiResult.getPois().size()){
                currentPage = 0;
                if(results.toString().equals("")){
                    return;
                }
                Intent intent = new Intent(MainActivity.this, ShowResultActivity.class);
                intent.putExtra("Data", results.toString());
                intent.putExtra("Count", getTypeCounts());
                startActivity(intent);
                hasStarted = true;
                return;
            }

            currentPage++;

            ArrayList<PoiItem> pois = poiResult.getPois();
            for(PoiItem poiItem: pois){
                String typeName = poiItem.getTypeDes().split(";")[0];
                Integer count = typeCounts.get(typeName);
                if(null == count){
                    count = 0;
                }
                typeCounts.put(typeName, count + 1);
                results.append(poiItem.toString()).append(",")
                        .append(typeName ).append(",")
                        .append(GCJ2WGSUtils.WGSLat(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude())).append(",")
                        .append(GCJ2WGSUtils.WGSLon(poiItem.getLatLonPoint().getLatitude(), poiItem.getLatLonPoint().getLongitude())).append("\n");
            }

            if(currentPage == 40){
                currentPage = 0;
                if(results.toString().equals("")){
                    return;
                }
                Intent intent = new Intent(MainActivity.this, ShowResultActivity.class);
                intent.putExtra("Data", results.toString());
                intent.putExtra("Count", getTypeCounts());
                startActivity(intent);
            }

        }else{
            Toast.makeText(this, "获取失败，请检查网络状态", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    private void draw(List<LatLng> points){
        if (null == points){
            return;
        }

        if(1 == points.size()){
            drawMarker(points.get(0));
            return;
        }

        if(2 == points.size()){
            drawMarker(points.get(points.size() - 1));
            drawLine(points);
            return;
        }

        if(points.size() >= 3){
            drawMarker(points.get(points.size() - 1));
            drawLine(points);
            drawPolygon(points);
        }
    }

    private void drawMarker(LatLng point){
        if(null == point){
            return;
        }
        final Marker marker = aMap.addMarker(new MarkerOptions().position(point).snippet("DefaultMarker"));
        markers.push(marker);
    }

    private void drawLine(List<LatLng> points){
        if(null != polyline){
            polyline.remove();
        }

        polyline = aMap.addPolyline(new PolylineOptions().addAll(points).width(10).color(Color.argb(50, 135,206,255)));

    }

    private void drawPolygon(List<LatLng> points){
        if(null != polygon){
            polygon.remove();
        }

        PolygonOptions polygonOptions = new PolygonOptions();
        polygonOptions.addAll(points);
        polygonOptions.strokeWidth(15) // 多边形的边框
                .strokeColor(Color.argb(50, 135,206,255)) // 边框颜色
                .fillColor(Color.argb(30, 255, 40, 90));   // 多边形的填充色

        polygon = aMap.addPolygon(polygonOptions);
    }

    private String getTypeCounts(){
        int all = 0;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("数据描述：\n");
        for (String typeName : typeCounts.keySet()) {

            all += typeCounts.get(typeName);

            stringBuilder.append(typeName).append(" : ").append(typeCounts.get(typeName)).append("\n");
        }
        stringBuilder.append("共 ").append(all).append("条数据");
        return stringBuilder.toString();
    }

}
